import ASN1 from './asn1'
import Base64 from './base64'
import Hex from './hex'
var maxLength = 10240,
  reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/,
  wantHex = id('wantHex'),
  area = id('area'),
  file = id('file'),
  examples = id('examples'),
  hash = null,
  dump = null,
  tree = null,
  dumpText = ''

require('./dom') // side effect: augment ASN1
if (!window.console || !window.console.log)
  // IE8 with closed developer tools
  window.console = { log: function () {} }
function id(elem) {
  return document.getElementById(elem)
}
function text(el, string) {
  if ('textContent' in el) el.textContent = string
  else el.innerText = string
}
function decode(der, offset) {  
  offset = offset || 0
  tree.innerHTML = ''
  dump.innerHTML = ''
  try {
    var asn1 = ASN1.decode(der, offset)    
    tree.appendChild(asn1.toDOM())
    dump.appendChild(asn1.toHexDOM())
    dumpText = dump.innerText
    var b64 = der.length < maxLength ? asn1.toB64String() : ''
    // if (area.value === '') area.value = Base64.pretty(b64)
    var endOffset = asn1.posEnd()
    if (endOffset < der.length) {
      var p = document.createElement('p')
      p.innerText =
        'Input contains ' + (der.length - endOffset) + ' more bytes to decode.'
      var button = document.createElement('button')
      button.innerText = 'try to decode'
      button.onclick = function () {
        decode(der, endOffset)
      }
      p.appendChild(button)
      tree.insertBefore(p, tree.firstChild)
    }
  } catch (e) {
    // text(tree, e)
    tree.innterText = ''
  }
}
export function decodeText(val, _tree, _dump) {
  debugger
  dump = _dump
  tree = _tree
  try {
    var der = reHex.test(val) ? Hex.decode(val) : Base64.unarmor(val)
    decode(der)
  } catch (e) {
    // text(tree, e)
    dump.innerHTML = ''
  }
  return dumpText
}
function decodeBinaryString(str) {
  var der
  try {
    if (reHex.test(str)) der = Hex.decode(str)
    else if (Base64.re.test(str)) der = Base64.unarmor(str)
    else der = str
    decode(der)
  } catch (e) {
    text(tree, 'Cannot decode file.')
    dump.innerHTML = ''
  }
}
// set up buttons
// id('butDecode').onclick = function () {
//   decodeText(area.value)
// }
// id('butClear').onclick = function () {
//   area.value = ''
//   file.value = ''
//   tree.innerHTML = ''
//   dump.innerHTML = ''
//   hash = window.location.hash = ''
// }
function stop(e) {
  e.stopPropagation()
  e.preventDefault()
}
function dragAccept(e) {
  stop(e)
  if (e.dataTransfer.files.length > 0) read(e.dataTransfer.files[0])
}
